Imports System.Reflection
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO
Imports System.Net

Public Class Util

    Public Shared Function CreateMessage(ByVal msgType As String, ByVal msgText As String, ByVal msgSender As String, ByVal payload As Object) As Byte()
        Dim serializer As New XmlSerializer(GetType(MessageClass))
        Dim msgId As System.Guid = System.Guid.NewGuid()
        Dim m As MessageClass
        m = New MessageClass(msgId, msgType, msgText, msgSender, payload)
        'Dim bf As BinaryFormatter = New BinaryFormatter
        Dim strm As MemoryStream = New MemoryStream
        Try
            'bf.Serialize(strm, m)
            serializer.Serialize(strm, m)
            'serializer.Serialize(New XmlTextWriter(strm, System.Text.Encoding.UTF8), m)
        Catch ex As SerializationException
            Console.WriteLine(ex.ToString)
        End Try
        Return strm.ToArray()
    End Function

    Public Shared Function RetrieveMessage(ByVal bytMsg As Byte()) As MessageClass
        Dim serializer As New XmlSerializer(GetType(MessageClass))
        Dim m As MessageClass
        Dim strm As MemoryStream
        strm = New MemoryStream(bytMsg)
        Dim f As BinaryFormatter = New BinaryFormatter
        Try
            'm = DirectCast(f.Deserialize(strm), MessageClass)
            m = DirectCast(serializer.Deserialize(strm), MessageClass)
            Return m
        Catch e As SerializationException
            Console.WriteLine(e.ToString)
            Return Nothing
        End Try
    End Function

    Public Shared Function CreateDefaultMessage() As MessageClass
        Dim msgobj As MessageClass = New MessageClass
        msgobj.MessageType = "UBuildMessage"
        msgobj.MessageText = ""
        msgobj.MessageSender = System.Net.Dns.GetHostName()
        msgobj.MessageSenderType = MessageClass.MsgSenderType.CLIENT
        msgobj.Payload = Nothing
        Return msgobj
    End Function


End Class


